<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统 - 分类管理</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        body {
            padding-top: 56px;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .sidebar {
            min-height: calc(100vh - 56px);
            position: fixed;
            top: 56px;
            left: 0;
            width: 200px;
            z-index: 100;
            padding: 20px 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #343a40;
        }
        .sidebar .nav-link {
            color: #ddd;
            padding: 0.5rem 1rem;
        }
        .sidebar .nav-link:hover {
            color: #fff;
            background-color: rgba(255, 255, 255, 0.1);
        }
        .sidebar .nav-link.active {
            color: #fff;
            background-color: rgba(255, 255, 255, 0.2);
        }
        .sidebar .nav-link i {
            margin-right: 8px;
        }
        .main-content {
            margin-left: 200px;
            padding: 20px;
            flex: 1;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
        <a class="navbar-brand" href="${pageContext.request.contextPath}/admin">
            <i class="fas fa-dumbbell"></i> 体育商城后台
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="${pageContext.request.contextPath}/" target="_blank">
                        <i class="fas fa-external-link-alt"></i> 访问前台
                    </a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown">
                        <i class="fas fa-user-circle"></i> ${adminUser}
                    </a>
                    <div class="dropdown-menu dropdown-menu-right">
                        <a class="dropdown-item" href="${pageContext.request.contextPath}/admin/logout">
                            <i class="fas fa-sign-out-alt"></i> 退出登录
                        </a>
                    </div>
                </li>
            </ul>
        </div>
    </nav>

    <!-- 侧边栏 -->
    <jsp:include page="sidebar.jsp" />

    <!-- 主要内容 -->
    <div class="main-content">
        <div class="container-fluid">
            <!-- 标题行 -->
            <div class="row mb-4">
                <div class="col-md-6">
                    <h2 class="mb-1">分类管理</h2>
                    <p class="text-muted">管理商品分类</p>
                </div>
                <div class="col-md-6 text-right">
                    <button class="btn btn-primary" data-toggle="modal" data-target="#categoryModal">
                        <i class="fas fa-plus"></i> 添加分类
                    </button>
                </div>
            </div>
            
            <!-- 分类列表 -->
            <div class="row">
                <div class="col-md-12">
                    <div class="card shadow-sm">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>名称</th>
                                            <th>图片</th>
                                            <th>描述</th>
                                            <th>排序</th>
                                            <th>父级分类</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="categoryTableBody">
                                        <tr>
                                            <td colspan="7" class="text-center">正在加载数据...</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 分类表单模态框 -->
    <div class="modal fade" id="categoryModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="categoryModalTitle">添加分类</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="categoryForm">
                        <input type="hidden" id="categoryId">
                        <div class="form-group">
                            <label for="categoryName">分类名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="categoryName" required>
                        </div>
                        <div class="form-group">
                            <label for="categoryDesc">分类描述</label>
                            <textarea class="form-control" id="categoryDesc" rows="3"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="categoryImage">分类图片</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="categoryImage" readonly>
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" id="uploadCategoryImageBtn">上传</button>
                                </div>
                            </div>
                            <div id="categoryPreviewContainer" class="mt-2" style="display: none;">
                                <img id="categoryImagePreview" class="img-thumbnail" style="max-height: 150px;">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="categorySortOrder">排序</label>
                            <input type="number" class="form-control" id="categorySortOrder" value="0" min="0">
                        </div>
                        <div class="form-group">
                            <label for="categoryParent">父级分类</label>
                            <select class="form-control" id="categoryParent">
                                <option value="0">无（顶级分类）</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveCategoryBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 图片上传模态框 -->
    <div class="modal fade" id="uploadCategoryImageModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">上传图片</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="uploadForm" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="categoryFileInput">选择图片</label>
                            <input type="file" class="form-control-file" id="categoryFileInput" name="file" accept="image/*" required>
                            <small class="form-text text-muted">推荐尺寸: 800x800 像素，最大文件大小: 2MB</small>
                        </div>
                        <div id="categoryUploadPreviewContainer" class="mt-3 d-none">
                            <img id="categoryUploadPreview" class="img-thumbnail" style="max-width: 100%; max-height: 200px;">
                        </div>
                    </form>
                    <div class="progress mt-3 d-none" id="categoryUploadProgress">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmCategoryUploadBtn">上传</button>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery 和 Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            let isEdit = false;
            
            // 加载分类列表
            function loadCategories() {
                $.get("${pageContext.request.contextPath}/admin/categories/list", function(res) {
                    console.log("API响应:", res); // 调试信息
                    if (res.code == 200 || res.success == true) {
                        renderCategories(res.data || []);
                    } else {
                        alert("加载分类失败: " + (res.message || res.msg));
                    }
                }).fail(function(jqXHR, textStatus, errorThrown) {
                    console.error("API请求失败:", textStatus, errorThrown);
                    alert("加载数据失败，请检查网络连接或联系管理员");
                });
            }
            
            // 渲染分类列表
            function renderCategories(categories) {
                const $tbody = $('#categoryTableBody');
                $tbody.empty();
                
                if (categories.length === 0) {
                    $tbody.html('<tr><td colspan="7" class="text-center">没有找到分类数据</td></tr>');
                    return;
                }
                
                const categoryMap = {};
                categories.forEach(function(category) {
                    categoryMap[category.id] = category;
                });
                
                categories.forEach(function(category) {
                    let parentName = '无';
                    if (category.parentId && category.parentId > 0) {
                        const parent = categoryMap[category.parentId];
                        if (parent) {
                            parentName = parent.name;
                        }
                    }
                    
                    const createTime = category.createTime ? new Date(category.createTime).toLocaleString() : '';
                    
                    let tr = '<tr>' +
                        '<td>' + category.id + '</td>' +
                        '<td>' + category.name + '</td>' +
                        '<td>' + (category.image ? '<img src="${pageContext.request.contextPath}' + category.image + '" height="40" />' : '') + '</td>' +
                        '<td>' + '' + '</td>' +
                        '<td>' + (category.sort || 0) + '</td>' +
                        '<td>' + parentName + '</td>' +
                        '<td>' + createTime + '</td>' +
                        '<td>' +
                            '<button class="btn btn-sm btn-outline-primary edit-btn" data-id="' + category.id + '">' +
                                '<i class="fas fa-edit"></i> 编辑' +
                            '</button> ' +
                            '<button class="btn btn-sm btn-outline-danger delete-btn" data-id="' + category.id + '">' +
                                '<i class="fas fa-trash"></i> 删除' +
                            '</button>' +
                        '</td>' +
                    '</tr>';
                    $tbody.append(tr);
                });
                
                // 更新父级分类选择器
                updateParentSelector(categories);
                
                // 绑定编辑按钮事件
                $('.edit-btn').click(function() {
                    const categoryId = $(this).data('id');
                    editCategory(categoryId, categories);
                });
                
                // 绑定删除按钮事件
                $('.delete-btn').click(function() {
                    const categoryId = $(this).data('id');
                    if (confirm('确定要删除这个分类吗？')) {
                        deleteCategory(categoryId);
                    }
                });
            }
            
            // 更新父级分类选择器
            function updateParentSelector(categories) {
                const $select = $('#categoryParent');
                $select.html('<option value="0">无（顶级分类）</option>');
                
                categories.forEach(function(category) {
                    $select.append('<option value="' + category.id + '">' + category.name + '</option>');
                });
            }
            
            // 编辑分类
            function editCategory(categoryId, categories) {
                isEdit = true;
                $('#categoryModalTitle').text('编辑分类');
                
                const category = categories.find(function(c) { return c.id == categoryId; });
                if (category) {
                    // 填充表单
                    $('#categoryId').val(category.id);
                    $('#categoryName').val(category.name);
                    $('#categoryDesc').val('');
                    $('#categoryImage').val(category.image || '');
                    $('#categorySortOrder').val(category.sort || 0);
                    $('#categoryParent').val(category.parentId || 0);
                    
                    // 显示图片预览（如果有图片）
                    if (category.image) {
                        $('#categoryImagePreview').attr('src', '${pageContext.request.contextPath}' + category.image);
                        $('#categoryPreviewContainer').show();
                    } else {
                        $('#categoryPreviewContainer').hide();
                    }
                    
                    // 打开模态框
                    $('#categoryModal').modal('show');
                } else {
                    alert('找不到该分类');
                }
            }
            
            // 删除分类
            function deleteCategory(categoryId) {
                $.ajax({
                    url: "${pageContext.request.contextPath}/admin/categories/delete/" + categoryId,
                    type: "POST",
                    success: function(res) {
                        if (res.code == 200 || res.success == true) {
                            alert("删除成功");
                            loadCategories();
                        } else {
                            alert("删除失败: " + (res.message || res.msg));
                        }
                    },
                    error: function() {
                        alert("删除失败，服务器错误");
                    }
                });
            }
            
            // 保存分类
            function saveCategory() {
                const category = {
                    name: $('#categoryName').val(),
                    image: $('#categoryImage').val(),
                    sort: parseInt($('#categorySortOrder').val()),
                    parentId: parseInt($('#categoryParent').val())
                };
                
                if (isEdit) {
                    category.id = parseInt($('#categoryId').val());
                }
                
                $.ajax({
                    url: "${pageContext.request.contextPath}/admin/categories/" + (isEdit ? "update" : "add"),
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(category),
                    success: function(res) {
                        if (res.code == 200 || res.success == true) {
                            alert(isEdit ? "更新成功" : "添加成功");
                            $('#categoryModal').modal('hide');
                            loadCategories();
                        } else {
                            alert((isEdit ? "更新失败: " : "添加失败: ") + (res.message || res.msg));
                        }
                    },
                    error: function() {
                        alert(isEdit ? "更新失败，服务器错误" : "添加失败，服务器错误");
                    }
                });
            }
            
            // 初始化事件
            
            // 添加分类按钮点击
            $('#categoryModal').on('show.bs.modal', function(e) {
                if (!isEdit) {
                    $('#categoryModalTitle').text('添加分类');
                    $('#categoryForm').trigger('reset');
                    $('#categoryId').val('');
                    $('#categoryParent').val(0);
                    $('#categoryPreviewContainer').hide();
                }
            });
            
            // 保存分类按钮点击
            $('#saveCategoryBtn').click(function() {
                // 表单验证
                if (!$('#categoryName').val()) {
                    alert('请输入分类名称');
                    return;
                }
                
                saveCategory();
            });
            
            // 图片上传按钮点击
            $('#uploadCategoryImageBtn').click(function() {
                $('#categoryFileInput').val('');
                $('#categoryUploadPreviewContainer').addClass('d-none');
                $('#uploadCategoryImageModal').modal('show');
            });
            
            // 图片文件改变时预览
            $('#categoryFileInput').change(function() {
                if (this.files && this.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        $('#categoryUploadPreview').attr('src', e.target.result);
                        $('#categoryUploadPreviewContainer').removeClass('d-none');
                    }
                    reader.readAsDataURL(this.files[0]);
                }
            });
            
            // 确认上传图片
            $('#confirmCategoryUploadBtn').click(function() {
                uploadCategoryImage();
            });
            
            // 上传分类图片
            function uploadCategoryImage() {
                const formData = new FormData();
                const fileInput = document.getElementById('categoryFileInput');
                
                if (fileInput.files.length === 0) {
                    alert('请选择图片');
                    return;
                }
                
                formData.append('file', fileInput.files[0]);
                
                // 显示上传进度
                $('#categoryUploadProgress').removeClass('d-none');
                
                $.ajax({
                    url: "${pageContext.request.contextPath}/admin/upload",
                    type: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        $('#categoryUploadProgress').addClass('d-none');
                        
                        if (res.code === 200 || res.success === true) {
                            $('#categoryImage').val(res.data);
                            $('#categoryImagePreview').attr('src', '${pageContext.request.contextPath}' + res.data);
                            $('#categoryPreviewContainer').show();
                            $('#uploadCategoryImageModal').modal('hide');
                        } else {
                            alert("上传失败: " + (res.message || res.msg));
                        }
                    },
                    error: function() {
                        $('#categoryUploadProgress').addClass('d-none');
                        alert("上传失败，服务器错误");
                    }
                });
            }
            
            // 初始加载
            loadCategories();
        });
    </script>
</body>
</html> 